﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace ChoViet.Lib.Common
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 14/06/2011
    /// </summary>
    public class BuiltTreeCollection
    {
        #region Public Member
        public TreeNodeCollection BuiltTreeNodeCollection(List<TreeNodeItem> listTreeItem)
        {
            return this.BuiltTreeNodeItem(listTreeItem);
        }


        public TreeNodeCollection BuiltTreeNodeCollection(List<TreeNodeItem> listTreeItem, int? selected)
        {
            try
            {
                if (selected.HasValue)
                    listTreeItem.SingleOrDefault(tree => tree.Value == selected.Value).Selected = true;

                return this.BuiltTreeNodeItem(listTreeItem);
            }
            catch (NullReferenceException nEx)
            {
                return this.BuiltTreeNodeItem(listTreeItem);
            }
        }

        public TreeNodeCollection BuiltTreeNodeCollection(List<TreeNodeItem> listTreeItem, List<int> listIDChecked)
        {
            foreach (int ID in listIDChecked)
            {
                listTreeItem.SingleOrDefault(tree => tree.Value == ID).Checked = true;
            }

            return this.BuiltTreeNodeItem(listTreeItem);
        }

        #endregion

        #region Private Member

        private TreeNodeCollection BuiltTreeNodeItem(List<TreeNodeItem> listTreeItem)
        {
            TreeNodeCollection treeCate = new TreeNodeCollection();
            foreach (TreeNodeItem treeItem in listTreeItem)
            {
                TreeNode node = new TreeNode(treeItem.Text, treeItem.Value.ToString());

                // Add node con voi nude goc moi
                if (!treeCate.Contains(node) && !treeItem.ParentID.HasValue)
                    treeCate.Add(this.BuiltTreeNodeItem(treeItem, listTreeItem));
            }

            return treeCate;
        }

        private TreeNode BuiltTreeNodeItem(TreeNodeItem nodeItem, List<TreeNodeItem> listTreeItem)
        {
            TreeNode node = new TreeNode(nodeItem.Text, nodeItem.Value.ToString());
            // Chọn node được select tương ứng cới cate được select
            if (nodeItem.Checked == true)
                node.Checked = true;
            if (nodeItem.Selected == true)
                node.Selected = true;

            List<TreeNodeItem> listTreeChild = listTreeItem.Where(tree => tree.ParentID.HasValue && nodeItem.Value == tree.ParentID.Value).ToList();

            if (listTreeChild.Count() <= 0)
                return node;
            else
                foreach (TreeNodeItem nItem in listTreeChild)
                {
                    node.ChildNodes.Add(this.BuiltTreeNodeItem(nItem, listTreeItem));
                }

            return node;
        }

        #endregion
    }
}
